import React, { Component } from 'react'
import {Breadcrumb, Button, Card, Form, Space, Input, Radio, Upload, Modal, message} from 'antd'
import { Link } from 'react-router-dom'
import Channel from 'components/Channel'
import TextArea from 'antd/lib/input/TextArea'
import {PlusOutlined} from '@ant-design/icons'
import { baseURL } from 'utils/request'
import { addArticles, getArticleById, updateArticles } from 'api/article'
export default class ArticlePublish extends Component {
  state={
    type: 1, // 封面类型
    fileList:[],// 上传图片
    previewVisible:false,// 是否预览
    previewUrl: '',// 预览图片
    id:this.props.match.params.id // 修改id
  }
  formRef=React.createRef()
  render() {
    return (
      <div>
        <Card title={
      <Breadcrumb>
    <Breadcrumb.Item>
    <Link to="/home">首页</Link> 
    </Breadcrumb.Item>
    <Breadcrumb.Item>
      {this.state.id?"编辑文章":"发布文章"}
    </Breadcrumb.Item>
  </Breadcrumb>
}>
<Form labelCol={{span:4}} size="large" onFinish={this.onFinish} initialValues={{type:this.state.type}} ref={this.formRef}>
  <Form.Item label="标题" name="title" rules={[{
    required:true,message:'标题不能为空'
  }]}>
    <Input style={{width:400}} placeholder="请输入文章标题"></Input>
  </Form.Item>

  <Form.Item label="频道" name="channel_id" rules={[{
    required:true,message:'请选择频道'
  }]}><Channel></Channel></Form.Item>

  <Form.Item label="封面" name="type">
    <Radio.Group onChange={this.changeType}>
      <Radio value={1}>单图</Radio>
      <Radio value={3}>三图</Radio>
      <Radio value={0}>无图</Radio>
    </Radio.Group>
  </Form.Item>
  <Form.Item wrapperCol={{offset:4}}>
    {
    this.state.type!==0 && (
    <Upload listType="picture-card" fileList={this.state.fileList} action={baseURL+"upload"} name="image" onChange={this.uploadImg} onPreview={this.handlePreview} beforeUpload={this.beforeUpload}>
      {this.state.fileList.length<this.state.type&&(<PlusOutlined></PlusOutlined>)}
    </Upload>
    )}
  </Form.Item>

  <Form.Item label="内容" name="content" rules={[{
    required:true,message:'内容不能为空'
  }]}>
    <TextArea rows={10} placeholder="请输入文章内容" />
  </Form.Item>

  <Form.Item wrapperCol={{offset:4}}>
    <Space>
  <Button type="primary" htmlType='submit'>{this.state.id?"编辑文章":"发布文章"}</Button>
  <Button onClick={this.addDraft}>存入草稿</Button>
  </Space>
  </Form.Item>
</Form>
        </Card>
        {/* 预览 */}
        <Modal visible={this.state.previewVisible} title={'图片预览'} footer={null} onCancel={this.handleCancel}>
        <img
          alt="example"
          style={{
            width: '100%',
          }}
          src={this.state.previewUrl}
        />
      </Modal>
        </div>
    )
  }
  // 发布
      onFinish=(values)=>{
        this.save(values,false)
    }
    // 切换图片类型
    changeType=(e)=>{
      this.setState({
        type:e.target.value,
        fileList:[]
      })
    }
    // 上传图片
    uploadImg=({fileList})=>{
      this.setState({
        fileList
      })
    }
    // 预览 
    handlePreview=(file)=>{
      this.setState({
        previewVisible:true,
        previewUrl:file.url||file.response.data.url
      })
    }
    // 关闭预览
    handleCancel=()=>{
      this.setState({
        previewVisible:false,
        previewUrl:''
      })
    }
    // 上传校验
    beforeUpload=(file)=>{
      if(file.size>=1024*500){
        message.warn('上传文件不得超过500kb')
        return Upload.LIST_IGNORE
      }
      if(!['image/png','image/jpeg'].includes(file.type)){
        message.warn('请上传jpg或png格式的图片')
        return Upload.LIST_IGNORE
      }
      return true
    }
    // 存入草稿
    addDraft= async()=>{
      // 表单校验并获取数据
      const values = await this.formRef.current.validateFields()
      this.save(values,true)
  }
  // 上传
  save= async(values,draft)=>{
     if(this.state.fileList.length!==this.state.type){
          return message.warn('请上传相应数量的图片')
        }
        const images = this.state.fileList.map(item=>{
          return item.url||item.response.data.url
        })
        if(this.state.id){
          // 修改
          await updateArticles({
        ...values,
        cover:{
          type:this.state.type,
          images
        },id:this.state.id
          },draft)
          message.success('修改成功')
        }else{
          // 添加
          await addArticles({
        ...values,
        cover:{
          type:this.state.type,
          images
        }
      },draft)
      message.success('添加成功')
        }
      this.props.history.push('/home/list')
  }
  async componentDidMount(){
    if(this.state.id){
      const res = await getArticleById(this.state.id)
      const values={
        ...res.data,
        type:res.data.cover.type,
      }
      // 回显
      this.formRef.current.setFieldsValue(values)
      this.setState({
        type:res.data.cover.type,
        fileList:res.data.cover.images.map(item=>{
          return {
            url:item
          }
        })
      })
    }
  }
}